package com.wondertek.mist.plugins;

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationClientOption.AMapLocationProtocol;
import com.amap.api.location.AMapLocationListener;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;

/**
 * 获取地理位置 有两种情况 1、不传递参数，安卓端实现定位，最后返回经纬度、地址 2、传递参数，安卓端获取并转换成经纬度，最后返回经纬度
 */
public class CFUBGetUserLocation extends CordovaPlugin 
{
	private Context context = null;
	private CallbackContext mCallbackContext = null;
	
	private AMapLocationClient locationClient = null;
	private AMapLocationClientOption locationOption = null;
	/**
	 * 默认的定位参数
	 * @since 2.8.0
	 * @author hongming.wang
	 *
	 */
	private AMapLocationClientOption getDefaultOption(){
		AMapLocationClientOption mOption = new AMapLocationClientOption();
		mOption.setLocationMode(AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
		mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
		mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
		mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
		mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
		mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
		mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
		AMapLocationClientOption.setLocationProtocol(AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
		mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
		mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
		mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
		return mOption;
	}
	/**
	 * 定位监听
	 */
	AMapLocationListener locationListener = new AMapLocationListener() {
		@Override
		public void onLocationChanged(AMapLocation location) {
			if (null != location) {

				StringBuffer sb = new StringBuffer();
				//errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
				String strResult = "";



				Message msg = new Message();
				Bundle bundle = new Bundle();
				if(location.getErrorCode() == 0){
					sb.append("定位成功" + "\n");
					sb.append("定位类型: " + location.getLocationType() + "\n");
					sb.append("经    度    : " + location.getLongitude() + "\n");
					sb.append("纬    度    : " + location.getLatitude() + "\n");
					sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
					sb.append("提供者    : " + location.getProvider() + "\n");

					sb.append("海    拔    : " + location.getAltitude() + "\n");
					sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
					sb.append("角    度    : " + location.getBearing() + "\n");
					//精度;location.getAltitude();
					// 获取当前提供定位服务的卫星个数
					sb.append("星    数    : " + location.getSatellites() + "\n");
					sb.append("国    家    : " + location.getCountry() + "\n");
					sb.append("省            : " + location.getProvince() + "\n");
					sb.append("市            : " + location.getCity() + "\n");
					sb.append("城市编码 : " + location.getCityCode() + "\n");
					sb.append("区            : " + location.getDistrict() + "\n");
					sb.append("区域 码   : " + location.getAdCode() + "\n");
					sb.append("地    址    : " + location.getAddress() + "\n");
					sb.append("兴趣点    : " + location.getPoiName() + "\n");
					//定位完成的时间
					///sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
					
					
					StringBuffer sbv = new StringBuffer();
					sbv.append("{");
					sbv.append("longitude");
					sbv.append(":");
					sbv.append(location.getLongitude());
					sbv.append(",");
					sbv.append("latitude");
					sbv.append(":");
					sbv.append(location.getLatitude());
					sbv.append(",");
					sbv.append("province");
					sbv.append(":");
					sbv.append(location.getProvince());
					sbv.append(",");
					sbv.append("city");
					sbv.append(":");
					sbv.append(location.getCity());
					sbv.append(",");
					sbv.append("district");
					sbv.append(":");
					sbv.append(location.getDistrict());					
					sbv.append(",");
					sbv.append("address");
					sbv.append(":");
					sbv.append(location.getAddress());					
					
					sbv.append("}");
					
/*					try {
						JSONObject args = new JSONObject(sbv.toString());
						args.get("longitude");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}*/
					strResult = location.getLongitude() + "," + location.getLatitude() + "," + location.getAltitude()+","+location.getAddress();
					bundle.putString("jw", strResult);
					///bundle.putString("jw", sbv.toString());
					msg.what = 0;

					msg.setData(bundle);
					handler.sendMessage(msg);
					
					stopLocation();
					
					
				} else {
					//定位失败
					msg.what = 1;
					sb.append("定位失败" + "\n");
					sb.append("错误码:" + location.getErrorCode() + "\n");
					sb.append("错误信息:" + location.getErrorInfo() + "\n");
					sb.append("错误描述:" + location.getLocationDetail() + "\n");
					msg.obj=sb.toString();
					///handler.sendMessage(msg);
					
					StringBuffer sbv = new StringBuffer();
					sbv.append("{");
					sbv.append("error");
					sbv.append(":");
					sbv.append(location.getErrorInfo());
					sbv.append("}");
					
					bundle.putString("jw", sbv.toString());
					msg.setData(bundle);

					
					handler.sendMessage(msg);
					
					
					
				}
			} else {
				Toast.makeText(context, "定位失败", Toast.LENGTH_LONG).show();
			}
		}
	};
	/**
	 * 开始定位
	 * 
	 * @since 2.8.0
	 * @author hongming.wang
	 *
	 */
	private void startLocation(){
		//根据控件的选择，重新设置定位参数
		///resetOption();
		// 设置定位参数
		locationClient.setLocationOption(locationOption);
		// 启动定位
		locationClient.startLocation();
	}
	
	/**
	 * 停止定位
	 * 
	 * @since 2.8.0
	 * @author hongming.wang
	 *
	 */
	private void stopLocation(){
		// 停止定位
		locationClient.stopLocation();
	}
	
	/**
	 * 销毁定位
	 * 
	 * @since 2.8.0
	 * @author hongming.wang
	 *
	 */
	private void destroyLocation(){
		if (null != locationClient) {
			/**
			 * 如果AMapLocationClient是在当前Activity实例化的，
			 * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
			 */
			locationClient.onDestroy();
			locationClient = null;
			locationOption = null;
		}
	}	
	private void initLocation(){
		//初始化client
		locationClient = new AMapLocationClient(context);
		locationOption = getDefaultOption();
		//设置定位参数
		locationClient.setLocationOption(locationOption);
		// 设置定位监听
		locationClient.setLocationListener(locationListener);
	}

	
	
	@Override
	public void initialize(CordovaInterface cordova, CordovaWebView webView)
	{
		// TODO Auto-generated method stub
		super.initialize(cordova, webView);
		context = cordova.getActivity();

		String sha1 = sHA1(context);

		initLocation();
	}

	public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
	{
		// TODO Auto-generated method stub
		mCallbackContext = callbackContext;
		///if (action.equals("getLocation"))
		{
			try {
				startLocation();
             }   
             catch (Exception e) {
             	Log.e("err", e.getMessage());
             }
		}
		return true;
	}
	private Handler handler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			// 没有错误，返回经纬度和地址
			if (msg.what == 0)
			{
				///Toast.makeText(context, "定位成功！！！", Toast.LENGTH_SHORT).show();
				mCallbackContext.success(msg.getData().getString("jw"));

			}
			// 有错误，提示错误
			else if (msg.what == 1)
			{
				//mCallbackContext.error(msg.getData().getString("jw"));
				Toast.makeText(context, msg.obj.toString(), Toast.LENGTH_SHORT).show();
			}
		};
	};


	public static String sHA1(Context context) {
	try {
		PackageInfo info = context.getPackageManager().getPackageInfo(
				context.getPackageName(), PackageManager.GET_SIGNATURES);
		byte[] cert = info.signatures[0].toByteArray();
		MessageDigest md = MessageDigest.getInstance("SHA1");
		byte[] publicKey = md.digest(cert);
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < publicKey.length; i++) {
			String appendString = Integer.toHexString(0xFF & publicKey[i])
					.toUpperCase(Locale.US);
			if (appendString.length() == 1)
				hexString.append("0");
			hexString.append(appendString);
			hexString.append(":");
		}
		String result = hexString.toString();
		return result.substring(0, result.length()-1);
	} catch (PackageManager.NameNotFoundException e) {
		e.printStackTrace();
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	return null;
}


}